<template>
  <div class="app-container">
    <div class="header">
      <div style="margin:15px 0px 0px 30px; font-size:22px">域名</div>
      <el-button style="margin:15px 30px 0px 0px" type="primary" @click="handleAdd">绑定已有域名</el-button>
    </div>
      <!-- <div style="margin:45px 0px 0px 30px; font-size:22px">域名列表</div> -->
    <div class="container">
      <el-table :data="domainNames" style="width: 100%">
    <el-table-column label="操作">
      <template slot-scope="scope">
        <el-tooltip v-if="scope.row.isDefault" class="item" effect="dark" content="当前仅有一个域名，请至少先绑定已有域名再更换默认域名" placement="top">
         <el-button
           size="mini"
           icon="el-icon-sort"
           type="text" @click="centerDialogVisible = true"></el-button>
       </el-tooltip>
        <el-tooltip class="item" effect="dark" content=" 删除" placement="top">
         <el-button
           size="mini"
           icon="el-icon-delete"
           type="text"
           @click.enter="handleDelDomainName(scope.row)"
            :disabled="scope.row.recordType === 'DEFAULT' || scope.row.isDefault"></el-button>
       </el-tooltip>
      </template>
    </el-table-column>
    <el-table-column label="域名">
      <template slot-scope="scope">
        <span style="margin-left: 10px">{{ scope.row.domainName }}</span>
      </template>
    </el-table-column>
    <el-table-column
      label="状态">
      <template slot-scope="scope">
        <el-tag size="medium">{{ scope.row.isDefault ? '已启用' : '未启用'}}</el-tag>
      </template>
    </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="{row}">
            <el-button size="mini"  @click="handleSettings(row)">设置</el-button>
          </template>
        </el-table-column>
  </el-table>
  </div>
    <el-dialog title="配置" :visible.sync="settingDialogVisible" center>
      <el-form ref="siteForm" :model="site" :rules="rules" label-width="160px">
        <el-form-item label="域名：">
          {{rowName}}
        </el-form-item>
        <el-form-item label="域名对应店铺名：" prop="siteName">
          <el-input v-model="site.siteName" placeholder="请输入店铺名称" style="width: 400px"/>
        </el-form-item>
        <el-form-item label="域名对应客服邮箱：" prop="serviceEmail">
          <el-input style="position: fixed;bottom: -9999px"></el-input>
          <el-input v-model="site.serviceEmail" placeholder="输入当前域名对应邮箱" auto-complete="off"
                    style="width: 400px"/>
        </el-form-item>
        <el-form-item label="PacyPay应用ID：">
          <el-input v-model="site.pacypayAppId" placeholder="请输入PacyPay应用ID" style="width: 400px"/>
        </el-form-item>
        <el-form-item label="域名对应店铺图标：" prop="faviconUrl" class="no-border pic">
          <upload-file accept="image/jpeg,image/jpg,image/png"
                       :fileType="['png', 'jpg', 'jpeg']"
                       :isShowTip="true"
                       :lazy="true"
                       :action="uploadPath"
                       title="图片"
                       v-model="site.faviconUrl"
          ></upload-file>
          <b style="color: #F56C6C">建议尺寸：32*32px</b>
        </el-form-item>
        <el-form-item label="域名对应店铺Logo：" prop="siteLogoUrl" class="no-border pic">
          <upload-file accept="image/jpeg,image/jpg,image/png"
                       :fileType="['png', 'jpg', 'jpeg']"
                       :isShowTip="true"
                       :lazy="true"
                       :action="uploadPath"
                       title="图片"
                       v-model="site.siteLogoUrl"
          ></upload-file>
          <b style="color: #F56C6C">建议尺寸：宽度250px, 建议上传LOGO图片的尺寸为设置的LOGO宽度的2倍</b>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSubmit('siteForm')" :loading="submitLoading">保存</el-button>
          <el-button @click="handleReset('siteForm')">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  <el-dialog title="更换默认域名" :visible.sync="centerDialogVisible" width="30%" center>
    <div class="domain-text">默认域名</div>
    <div class="radio-text">
      <el-radio-group  v-model="domainName">
          <el-radio :label="item.domainName" :key="item.id" v-for="item in availableDomainNames" >{{item.domainName}}{{item.isDefault ? '(当前默认域名)':''}}</el-radio>
      </el-radio-group>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="centerDialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="handleUpdateDefaultDomainName">确 定</el-button>
    </span>
  </el-dialog>
  </div>
</template>

<script>
import {page, updateDefaultDomainName, getAvailableDomainName, delDomainName, updateDomainSetting} from '@/api/domain';
import uploadFile from '@/components/Upload/uploadFile';
import axios from 'axios';
import {mapGetters} from 'vuex';

export default {
    name: 'domain-name-list',
    components: {uploadFile},
    data () {
        return {
            params: {},
            config: {},
            radio: '2',
            settingDialogVisible: false,
            settingVisible: false,
            listLoading: false,
            domainNames: [],
            domainName: '',
            availableDomainNames: [],
            centerDialogVisible: false,
            uploadPath: process.env.VUE_APP_BASE_API + '/upload-file',
            rowName: '',
            submitLoading: false,
            site: {
                pacypayAppId: null,
                id: null,
                faviconUrl: '',
                serviceEmail: '',
                siteLogoUrl: '',
                siteName: ''
            },
            rules: {
                siteName: [
                    {required: true, message: '请输入店铺名称', trigger: 'blur'},
                    {type: 'string', pattern: /^[a-zA-Z\d]+$/, message: '店铺名只支持英文或数字', trigger: 'blur'}
                ],
                serviceEmail: [
                    {required: true, message: '请输入客服邮箱', trigger: 'blur'},
                    {type: 'email', message: '邮箱格式不正确', trigger: 'blur'}
                ]
            }
        };
    },
    methods: {
        getData (params) {
            return new Promise((resolve, reject) => {
                page({...this.pageParams, ...params}).then((res) => {
                    resolve(res);
                });
            });
        },
        handleAdd () {
            this.$router.push({name: 'domain-name-add'});
        },
        handleDelDomainName (row) {
            this.$confirm('此操作将永久删除该域名, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.listLoading = true;
                delDomainName(row.id, this.siteId).then(res => {
                    if (res.code === '200') {
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        });
                        this.initData();
                    } else {
                        this.$message({type: 'error', message: '删除出错'});
                    }
                });
            }).catch(() => {

            });
        },
        handleUpdateDefaultDomainName () {
            // 更新已绑定域名
            if (this.domainName) {
                let data = {
                    domainName: this.domainName,
                    siteId: this.siteId
                };
                updateDefaultDomainName(data).then(res => {
                    this.$message({type: 'success', message: '更新成功'});
                    this.centerDialogVisible = false;
                    // this.$refs['el-search-table'].fetchHandler(this.pageParams, false);
                    this.initData();
                });
            } else {
                this.$message({type: 'error', message: '域名为空'});
            }
        },
        handleGetAvailableDomainName () { // 获取默认域名
            let data = {
                siteId: this.siteId
            };
            getAvailableDomainName(data).then(res => {
                this.availableDomainNames = res.data;
                if (this.availableDomainNames) {
                    for (var d in this.availableDomainNames) {
                        let o = this.availableDomainNames[d];
                        if (o.isDefault) {
                            this.domainName = o.domainName;
                            return;
                        }
                    }
                }
            });
        },
        initData () {
            this.params.pageSize = 100;
            this.params.siteId = this.siteId;

            this.getData(this.params).then(res => {
                this.domainNames = res.data;
            });
            this.handleGetAvailableDomainName();
        },
        handleSettings (row) {
            this.rowName = row.domainName;
            this.site = Object.assign({
                id: null,
                faviconUrl: '',
                serviceEmail: '',
                siteLogoUrl: '',
                siteName: ''
            }, row);
            this.settingDialogVisible = true;
        },
        handleSubmit (name) {
            this.$refs[name].validate(valid => {
                if (valid) {
                    this.submitLoading = true;
                    updateDomainSetting(this.site).then(async res => {
                        this.submitLoading = false;
                        this.$message.success('更新成功');
                        this.settingDialogVisible = false;
                        this.initData();
                        this.$store.dispatch('CLEAR_FRONT_CACHE');
                    }).catch(() => {
                        this.submitLoading = false;
                    });
                }
            });
        },
        handleReset (name) {
            this.settingDialogVisible = false;
            this.$refs[name].resetFields();
            this.$router.push({name: 'site-list'});
        }
    },
    mounted () {
        this.initData();
    },
    computed: {
        ...mapGetters(['siteList']),
        siteInfo () {
            let info = this.siteList.find(res => res.id === Number(this.siteId));
            return info;
        },
        siteId () {
            return this.$store.state.user.siteId;
        }
    }
};
</script>

<style lang="scss" scoped>
.header{
  margin: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  .head_left{
    display: inline-flex;
    align-items: center;
    line-height: 20px;
    .title{
      color: #30354d;
      font-size: 22px;
      margin-right: 24px;
    }
    .desc{
      font-size: 14px;
      color: #7e849c;
    }
  }
}
.container {
  margin: 30px;
  display: flex;
  flex-direction: row;
//   padding: 40px;
  // align-items: center;
  background-color: #f8f7f7;
}
.content{
    margin: 15px 0 0 30px;
}
.domain-text{
  height: 30px;
  margin: 0 0 20px 0;
  padding: 0px 0 10px 0;
}
.radio-text{
  display: flex;
  flex-direction: column;
  line-height: 30px;
}
</style>
